package com.ruoyi.msg.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.text.CharSequenceUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.msg.domain.MsgDcwjTk;
import com.ruoyi.msg.domain.MsgDcwjTkXx;
import com.ruoyi.msg.domain.MsgDcwjWj;
import com.ruoyi.msg.domain.MsgDcwjWjTk;
import com.ruoyi.msg.domain.bo.MsgDcwjWjBo;
import com.ruoyi.msg.domain.bo.WjXtBatchBo;
import com.ruoyi.msg.domain.vo.MsgDcwjTkVo;
import com.ruoyi.msg.domain.vo.MsgDcwjWjVo;
import com.ruoyi.msg.domain.vo.TkXxDetailVo;
import com.ruoyi.msg.mapper.MsgDcwjTkMapper;
import com.ruoyi.msg.mapper.MsgDcwjTkXxMapper;
import com.ruoyi.msg.mapper.MsgDcwjWjMapper;
import com.ruoyi.msg.mapper.MsgDcwjWjTkMapper;
import com.ruoyi.msg.service.IMsgDcwjWjService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.compress.utils.Lists;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 问卷管理Service业务层处理
 *
 * @author xiaohao
 * @date 2023-02-02
 */
@RequiredArgsConstructor
@Service
public class MsgDcwjWjServiceImpl implements IMsgDcwjWjService {

    private final MsgDcwjWjMapper baseMapper;
    private final MsgDcwjWjTkMapper wjTkMapper;
    private final MsgDcwjTkMapper tkMapper;
    private final MsgDcwjTkXxMapper tkXxMapper;

    @Override
    public List<TkXxDetailVo> selectedList(Long id, String name, String type) {
        List<TkXxDetailVo> resultList = Lists.newArrayList();
        // 查询当前问卷的【已选】题库ids
        List<MsgDcwjWjTk> list = wjTkMapper.selectList(
            Wrappers.<MsgDcwjWjTk>lambdaQuery()
                .select(MsgDcwjWjTk::getId, MsgDcwjWjTk::getTkId, MsgDcwjWjTk::getSort)
                .eq(MsgDcwjWjTk::getWjId, id)
                .orderByAsc(MsgDcwjWjTk::getSort)
        );
        if (CollUtil.isNotEmpty(list)) {
            Set<Long> tkIds = list.stream().map(MsgDcwjWjTk::getTkId).collect(Collectors.toSet());
            // 查询对应题库信息
            LambdaQueryWrapper<MsgDcwjTk> wrapper = Wrappers.lambdaQuery();
            if (CharSequenceUtil.isNotBlank(name)) {
                wrapper.like(MsgDcwjTk::getTopic, name);
            }
            if (CharSequenceUtil.isNotBlank(type)) {
                wrapper.eq(MsgDcwjTk::getType, type);
            }
            List<MsgDcwjTk> tkList = tkMapper.selectList(
                Wrappers.<MsgDcwjTk>lambdaQuery()
                    .in(MsgDcwjTk::getId, tkIds)
            );
            // 查询对应的选项信息
            List<MsgDcwjTkXx> optionList = tkXxMapper.selectList(
                Wrappers.<MsgDcwjTkXx>lambdaQuery()
                    .in(MsgDcwjTkXx::getTkId, tkIds)
            );
            // 组装数据
            if (CollUtil.isNotEmpty(tkList)) {
                tkList.forEach(tkInfo -> {
                    TkXxDetailVo detailVo = BeanUtil.toBean(tkInfo, TkXxDetailVo.class);
                    // 绑定问卷题库关系id （用于问卷中题目的删除和排序操作）
                    list.stream().filter(t -> t.getTkId().equals(detailVo.getId())).findFirst().ifPresent(wjTk -> {
                        detailVo.setWjTkId(wjTk.getId());
                        detailVo.setSort(wjTk.getSort());
                    });
                    // 绑定对应选项信息
                    if (CollUtil.isNotEmpty(optionList)) {
                        List<TkXxDetailVo.OptionsDTO> optionsDTOList = Lists.newArrayList();
                        List<MsgDcwjTkXx> tkXxList = optionList.stream()
                            .filter(option -> detailVo.getId().equals(option.getTkId()))
                            .sorted(Comparator.comparing(MsgDcwjTkXx::getSort))
                            .collect(Collectors.toList());
                        tkXxList.forEach(option -> {
                            TkXxDetailVo.OptionsDTO optionsDTO = BeanUtil.toBean(option, TkXxDetailVo.OptionsDTO.class);
                            optionsDTOList.add(optionsDTO);
                        });
                        detailVo.setOptions(optionsDTOList);
                    }
                    resultList.add(detailVo);
                });
            }
        }
        // 数据排序
        return resultList.stream().sorted(Comparator.comparing(TkXxDetailVo::getSort)).collect(Collectors.toList());
    }

    @Override
    public TableDataInfo<MsgDcwjTkVo> chooseList(Long id, PageQuery pageQuery) {
        LambdaQueryWrapper<MsgDcwjTk> wrapper = Wrappers.lambdaQuery();
        // 查询当前问卷的【已选】题库ids
        List<MsgDcwjWjTk> list = wjTkMapper.selectList(
            Wrappers.<MsgDcwjWjTk>lambdaQuery()
                .select(MsgDcwjWjTk::getTkId)
                .eq(MsgDcwjWjTk::getWjId, id)
                .orderByAsc(MsgDcwjWjTk::getSort)
        );
        if (CollUtil.isNotEmpty(list)) {
            List<Long> tkIds = list.stream().map(MsgDcwjWjTk::getTkId).collect(Collectors.toList());
            // 查询对应【未选】的题库信息列表
            wrapper.notIn(MsgDcwjTk::getId, tkIds);
        }
        Page<MsgDcwjTkVo> result = tkMapper.selectVoPage(pageQuery.build(), wrapper);
        return TableDataInfo.build(result);
    }

    @Override
    public void saveBatch(WjXtBatchBo bo) {
        // 自动排序
        Long count = wjTkMapper.selectCount(
            Wrappers.<MsgDcwjWjTk>lambdaQuery()
                .eq(MsgDcwjWjTk::getWjId, bo.getWjId())
        );
        Integer sort = Convert.toInt(count);
        List<MsgDcwjWjTk> list = bo.getList();
        for (MsgDcwjWjTk wjTk : list) {
            wjTk.setSort(sort++);
            wjTk.setCreateBy(LoginHelper.getUserId().toString());
        }
        // 批量保存
        wjTkMapper.insertBatch(list);
    }

    /**
     * 查询问卷管理
     */
    @Override
    public MsgDcwjWjVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询问卷管理列表
     */
    @Override
    public TableDataInfo<MsgDcwjWjVo> queryPageList(MsgDcwjWjBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<MsgDcwjWj> lqw = buildQueryWrapper(bo);
        Page<MsgDcwjWjVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询问卷管理列表
     */
    @Override
    public List<MsgDcwjWjVo> queryList(MsgDcwjWjBo bo) {
        LambdaQueryWrapper<MsgDcwjWj> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<MsgDcwjWj> buildQueryWrapper(MsgDcwjWjBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<MsgDcwjWj> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getName()), MsgDcwjWj::getName, bo.getName());
        lqw.eq(bo.getStartTime() != null, MsgDcwjWj::getStartTime, bo.getStartTime());
        lqw.eq(bo.getEndTime() != null, MsgDcwjWj::getEndTime, bo.getEndTime());
        lqw.eq(StringUtils.isNotBlank(bo.getEnabled()), MsgDcwjWj::getEnabled, bo.getEnabled());
        return lqw;
    }

    /**
     * 新增问卷管理
     */
    @Override
    public Boolean insertByBo(MsgDcwjWjBo bo) {
        MsgDcwjWj add = BeanUtil.toBean(bo, MsgDcwjWj.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改问卷管理
     */
    @Override
    public Boolean updateByBo(MsgDcwjWjBo bo) {
        MsgDcwjWj update = BeanUtil.toBean(bo, MsgDcwjWj.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(MsgDcwjWj entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除问卷管理
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
